package com.example.java_gobang.controller;

import com.example.java_gobang.mapper.UserMapper;
import com.example.java_gobang.model.User;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;


@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserMapper userMapper;

    @RequestMapping(value = "/login", method = RequestMethod.POST, produces = "application/json")
    public Object login(String username, String password, HttpServletRequest request){
        // 关键操作就是根据username去数据库中查找，如果能找到匹配的用户并且密码也一致，就认为登录成功
        User user = userMapper.selectByName(username);
        if(user == null || !user.getPassword().equals(password)){
            //登录失败
            log.warn(username + " 登录失败!");
            return new User();
        }
        HttpSession httpsession = request.getSession(true);
        httpsession.setAttribute("user", user);
        return user;
    }

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public Object register(String username, String password){
        try{
            User user = new User();
            user.setUsername(username);
            user.setPassword(password);
            userMapper.insert(user);
            return user;
        } catch(DuplicateKeyException e) {
            return new User();
        }
    }

    @RequestMapping(value = "/userInfo", method = RequestMethod.GET)
    public Object getUserInfo(HttpServletRequest req){
        HttpSession httpSession = req.getSession(false);
        if(httpSession == null){
            return new User();
        }
        //这个对象不是最新的，直接用这个对象去找
        User user = (User)httpSession.getAttribute("user");
        user = userMapper.selectByName(user.getUsername());
        return user;
    }
}
